package com.swotxu.mall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swotxu.common.constant.OrderConstant;
import com.swotxu.common.exception.NoStockException;
import com.swotxu.common.utils.PageUtils;
import com.swotxu.common.utils.Query;
import com.swotxu.common.utils.R;
import com.swotxu.common.utils.RedisUtils;
import com.swotxu.common.vo.MemberRespVo;
import com.swotxu.mall.order.dao.OrderDao;
import com.swotxu.mall.order.entity.OrderEntity;
import com.swotxu.mall.order.entity.OrderItemEntity;
import com.swotxu.mall.order.enume.OrderStatusEnum;
import com.swotxu.mall.order.feign.CartFeignService;
import com.swotxu.mall.order.feign.MemberFeignService;
import com.swotxu.mall.order.feign.ProductFeignService;
import com.swotxu.mall.order.feign.WmsFeignService;
import com.swotxu.mall.order.interceptor.LoginUserInterceptor;
import com.swotxu.mall.order.service.OrderItemService;
import com.swotxu.mall.order.service.OrderService;
import com.swotxu.mall.order.to.OrderCreateTo;
import com.swotxu.mall.order.vo.FareVo;
import com.swotxu.mall.order.vo.MemberAddressVo;
import com.swotxu.mall.order.vo.OrderConfirmVo;
import com.swotxu.mall.order.vo.OrderItemVo;
import com.swotxu.mall.order.vo.OrderSubmitVo;
import com.swotxu.mall.order.vo.SkuStockVo;
import com.swotxu.mall.order.vo.SpuInfoVo;
import com.swotxu.mall.order.vo.SubmitOrderResponseVo;
import com.swotxu.mall.order.vo.WareSkuLockVo;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    WmsFeignService wmsFeignService;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    OrderItemService orderItemService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        log.info("main、订单结算页请求，主线程Id[{}]", Thread.currentThread().getId());

        //获取之前的请求
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //1、远程查询所有的收货地址列表
            log.info("-- 订单结算页请求，member线程Id[{}]", Thread.currentThread().getId());
            //每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            R r = memberFeignService.getAddress(memberRespVo.getId());
            if (r.isOk()) {
                confirmVo.setAddress(r.getData(new TypeReference<List<MemberAddressVo>>() {
                }));
            }
        }, executor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //2、远程查询购物车所有选中的购物项
            log.info("-- 订单结算页请求，cart线程Id[{}]", Thread.currentThread().getId());
            //每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            R r = cartFeignService.getCurrentUserCartItems();
            if (r.isOk()) {
                confirmVo.setItems(r.getData(new TypeReference<List<OrderItemVo>>() {
                }));
            }
            //feign在远程调用之前要构造请求，调用很多的拦截器
            //RequestInterceptor interceptor : requestInterceptors
        }, executor).thenRunAsync(() -> {
            // 查询商品有货无货
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> skuIds = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());

            //TODO 一定要启动库存服务，否则库存查不出。
            R hasStock = wmsFeignService.getSkusHasStock(skuIds);
            if (hasStock.isOk()) {
                List<SkuStockVo> data = hasStock.getData(new TypeReference<List<SkuStockVo>>() {
                });
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(map);
            }
        }, executor);

        //3、查询用户积分
        confirmVo.setIntegration(memberRespVo.getIntegration());

        //4、其他数据自动计算

        //5、防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.getOrderToken(memberRespVo.getId()), token, 30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);

        CompletableFuture.allOf(getAddressFuture, cartFuture).get();

        return confirmVo;
    }

    //本地事务，在分布式系统，只能控制住自己的回滚，控制不了其他服务的回滚
    //分布式事务： 最大原因。网络问题+分布式机器。
    //(isolation = Isolation.REPEATABLE_READ)
    //REQUIRED、REQUIRES_NEW
    @GlobalTransactional  //高并发
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
        response.setCode(0);
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        //1、验证令牌【令牌的对比和删除必须保证原子性】
        //原子验证令牌和删除令牌 0-令牌失败 - 1删除成功
        String orderToken = vo.getOrderToken();
        Long result = redisUtils.compareDelete(OrderConstant.getOrderToken(memberRespVo.getId()), orderToken);
        //令牌验证失败
        if (result == 0L) {
            response.setCode(1);
            return response;
        }
        //令牌验证成功
        //下单：去创建订单，验令牌，验价格，锁库存...
        //1、创建订单，订单项等信息
        OrderCreateTo order = createOrder(vo);
        //2、验价
        BigDecimal payAmount = order.getOrder().getPayAmount();
        if (payAmount.compareTo(vo.getPayPrice()) != 0) {
            response.setCode(2);
            return response;
        }
        //金额对比
        //....
        //TODO 3、保存订单
        saveOrder(order);
        //4、准备库存锁定。只要有异常回滚订单数据。
        // 订单号，所有订单项（skuId，skuName，num）
        WareSkuLockVo lockVo = new WareSkuLockVo();
        lockVo.setOrderSn(order.getOrder().getOrderSn());
        List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
            OrderItemVo itemVo = new OrderItemVo();
            itemVo.setSkuId(item.getSkuId());
            itemVo.setCount(item.getSkuQuantity());
            itemVo.setTitle(item.getSkuName());
            return itemVo;
        }).collect(Collectors.toList());
        lockVo.setLocks(locks);
        //TODO 4、远程锁库存
        //库存成功了，但是网络原因超时了，订单回滚，库存不滚。
        //为了保证高并发。库存服务自己回滚。可以发消息给库存服务；
        //库存服务本身也可以使用自动解锁模式  消息
        R r = wmsFeignService.orderLockStock(lockVo);
        if (!r.isOk()) {
            //锁定失败
            throw new NoStockException(r.getMessage());
        }
        //锁成功了
        response.setOrder(order.getOrder());

        //TODO 5、远程扣减积分 出异常
        int i = 10/0; //订单回滚，库存不滚
        //订单创建成功发送消息给MQ
//        rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
        //TODO 6、清除购物车已经下单的商品
        return response;
    }

    /**
     * 创建订单
     *
     * @return 订单实体
     */
    private OrderCreateTo createOrder(OrderSubmitVo vo) {
        OrderCreateTo createTo = new OrderCreateTo();
        //1、生成订单号
        String orderSn = IdWorker.getTimeId();
        //创建订单号
        OrderEntity orderEntity = buildOrder(orderSn, vo.getAddrId());

        //2、获取到所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);

        //3、计算价格、积分等相关
        computePrice(orderEntity, itemEntities);

        createTo.setOrder(orderEntity);
        createTo.setOrderItems(itemEntities);

        return createTo;
    }

    /**
     * 构建订单实体
     *
     * @param orderSn 订单号
     * @param addrId  收获地址id
     * @return 订单实体
     */
    private OrderEntity buildOrder(String orderSn, Long addrId) {
        MemberRespVo respVo = LoginUserInterceptor.loginUser.get();
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(respVo.getId());

        //获取收货地址信息
        R fare = wmsFeignService.getFare(addrId);
        if (fare.isOk()) {
            FareVo fareResp = fare.getData(new TypeReference<FareVo>() {
            });
            entity.setFreightAmount(fareResp.getFare());
            //设置收货人信息
            entity.setReceiverCity(fareResp.getAddress().getCity());
            entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
            entity.setReceiverName(fareResp.getAddress().getName());
            entity.setReceiverPhone(fareResp.getAddress().getPhone());
            entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
            entity.setReceiverProvince(fareResp.getAddress().getProvince());
            entity.setReceiverRegion(fareResp.getAddress().getRegion());
        }
        //设置订单的相关状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);
        return entity;
    }

    /**
     * 构建所有订单项数据
     *
     * @return 订单项数据
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后确定每个购物项的价格
        R cartItems = cartFeignService.getCurrentUserCartItems();
        if (!cartItems.isOk()) {
            return Collections.emptyList();
        }
        List<OrderItemVo> currentUserCartItems = cartItems.getData(new TypeReference<List<OrderItemVo>>() {
        });
        return currentUserCartItems.stream().map(cartItem -> buildOrderItem(cartItem, orderSn)).collect(Collectors.toList());
    }

    /**
     * 构建某一个订单项
     *
     * @param cartItem 购物车实体
     * @return 订单项实体
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem, String orderSn) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1、订单信息：订单号 v
        itemEntity.setOrderSn(orderSn);
        //2、商品的SPU信息  V
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setCategoryId(data.getCatalogId());
        //3、商品的sku信息  v
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //4、优惠信息[不做]
        //5、积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        //6、订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额。 总额-各种优惠
        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = orign.subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);

        return itemEntity;
    }

    /**
     * 验价 - 计算价格相关
     *
     * @param orderEntity  订单实体
     * @param itemEntities 订单项
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0");

        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        //订单的总额，叠加每一个订单项的总额信息
        for (OrderItemEntity entity : itemEntities) {
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            total = total.add(entity.getRealAmount());
            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
//            Integer growth = entity.getGiftGrowth();
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));
        }
        //1、订单价格相关
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);

        //设置积分等信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setDeleteStatus(0);//未删除
    }

    /**
     * 保存订单数据
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        // 注：seata0.7版本，不支持批量插入，特改为循环插入
//        orderItemService.saveBatch(order.getOrderItems());
        order.getOrderItems().forEach(orderItemService::save);
    }
}